/* 
 * Copyright (C) 2012 UTSChedule
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package utsc.apps.utschedule.ui.activities;

import java.lang.ref.WeakReference;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;

import utsc.apps.utschedule.R;
import utsc.apps.utschedule.classes.Assignment;
import utsc.apps.utschedule.classes.Course;
import utsc.apps.utschedule.classes.UofTGrade;
import utsc.apps.utschedule.services.NotifyService;
import utsc.apps.utschedule.ui.InputDialogFragment;
import utsc.apps.utschedule.ui.InputDialogFragment.OnInputListener;
import utsc.apps.utschedule.ui.MessageDialogFragment;
import utsc.apps.utschedule.ui.interfaces.TimetableActivity;
import utsc.apps.utschedule.util.AppUtils;
import utsc.apps.utschedule.util.TimetableHelper;
import utsc.apps.utschedule.util.Validator;
import utsc.apps.utschedule.util.database.DatabaseManager;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.LayerDrawable;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * This is an activity to show the detail information of an {@link utsc.apps.utschedule.classes.Assignment Assignment}.
 *
 */
public class AssignmentDetailActivity extends GenericDetailActivity implements OnClickListener, OnInputListener {

	private Course _course;
	private int _courseID;
	private Assignment _assignment;
	public static final String TAG="utsc.apps.utschedule.ui.activities.AssignmentDetailActivity";
	public static final String REQUEST_COURSE_KEY="requestCourse";
	private TextView _txtCourse;
	private TextView _txtDesc;
	private TextView _txtDueDate;
	private TextView _txtWeight;
	private TextView _txtMarkGrade;
	private boolean _updated=true;
	private Button _btnUpdateMarks;
	private boolean _fromNotification=false;
	private Validator _validator=Validator.newInstance(TAG);
	private double _currentInputMark=0;
	private double _currentInputTotal=0;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.activity_assignment_detail);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        
        Intent requestIntent=getIntent();
		if (requestIntent!=null) {
			//always get the assignment object from db
			_assignment=DatabaseManager.getInstance(getApplicationContext()).getAssignment(requestIntent.getIntExtra(Assignment.ASSUID, -1));
			
			if (_assignment!=null) {
				//determine if the activity is openned from a notification
				_fromNotification=requestIntent.getBooleanExtra(NotifyService.FROM_NOTIFICATION, false);
				
				//if yes, we get the course id from the assignment object
				//otherwise, we should be able to get it from the intent
				_courseID=_assignment.get_course().get_courseID();
				_course=DatabaseManager.getInstance(getApplicationContext()).getCourse(_courseID);
				
				//setup the header and the detail content
				if (_course!=null && _assignment!=null) {
					_assignment.set_expired(requestIntent.getBooleanExtra(Assignment.EXPIRED, false));
					_color=_course.get_color();
					setupHeader();
					setupDetailContent();
				}else {
					throw new IllegalArgumentException("The required Assignment object is missing in the intent!");
				}
			}else {
				Toast.makeText(this, AppUtils.ERROR_MESSAGE_ASSIGNMENT_NOT_FOUND, Toast.LENGTH_LONG).show();
				finish();
			}
			
			
		}
    }


    @Override
	protected void onResume() {
		super.onResume();
		//see if we got an update
		//we refresh all the views and data
		if (!_updated) {
			_assignment=DatabaseManager.getInstance(getApplicationContext()).getAssignment(getIntent().getIntExtra(Assignment.ASSUID, 0));
			_assignment.refresh_grade();
			setupHeader();
			setupDetailContent();
			_updated=true;
		}
	}
    
    @Override
	public boolean onCreateOptionsMenu(Menu menu) {
    	super.onCreateOptionsMenu(menu);
        getSupportMenuInflater().inflate(R.menu.detail_menu_items, menu);
        return true;
    }
    
    @Override
    protected void onActivityResult(int arg0, int arg1, Intent arg2) {
    	super.onActivityResult(arg0, arg1, arg2);
    	if (arg1==RESULT_OK) {
			_updated=false;
		}
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
            	navigationUp();
                break;
            case R.id.edit:
            	Intent updateAssignmentIntent=_assignment.getObjectIntent();
            	updateAssignmentIntent.setClass(this, AssignmentFormActivity.class);
    			updateAssignmentIntent.putExtra("CourseAssignment", _assignment.get_course().get_courseID());
    			updateAssignmentIntent.putExtra("RequestCode", TimetableActivity.RESULT_UPDATE_ASSIGNMENT);
    			startActivityForResult(updateAssignmentIntent, TimetableActivity.RESULT_UPDATE_ASSIGNMENT);
            	break;
            case R.id.delete:
            	DatabaseManager.getInstance(this).deleteAssignmentById(_assignment.get_AssUID());
            	Intent deleteIntent=new Intent();
        		deleteIntent.putExtra("AssignmentCourseForResult", _courseID);
        		setResult(Activity.RESULT_OK, deleteIntent);
                finish();
            	break;
                //return true;
        }
        return true;//super.onOptionsItemSelected(item);
    }
    
    /**
     * A helper method to handle the proper navigation for different task stack situations.
     */
    private void navigationUp(){
    	if (_fromNotification) {
    		Intent intent=new Intent(this,AssignmentExamMainActivity.class);
    		intent.putExtra("fromActivity", TAG);
			NavUtils.navigateUpTo(this, new Intent(this,AssignmentExamMainActivity.class));
		}else {
			Intent resultIntent=new Intent();
    		resultIntent.putExtra("AssignmentCourseForResult", _courseID);
    		setResult(Activity.RESULT_OK, resultIntent);
            finish();
		}
    }
    
    @Override
    public void onBackPressed() {
    	navigationUp();
    }
    
    /**
     * {@inheritDoc }
     */
	@Override
	protected void setupHeader() {
		_detailHeader=(LinearLayout) findViewById(R.id.detail_header);
		if (_detailHeader!=null) {
			
			TextView title=(TextView) _detailHeader.findViewById(R.id.detail_header_title);
			LinearLayout detailColorIcon=(LinearLayout) _detailHeader.findViewById(R.id.detail_color_icon);
			title.setText(_assignment.get_Title());
			
			WeakReference<LayerDrawable> bg=AppUtils.getColorCustomizableDrawable(getApplicationContext(), R.drawable.bezel_border_bg, _color, 0, AppUtils.ALPHA);
			detailColorIcon.setBackgroundDrawable(bg.get());
			
			WeakReference<LayerDrawable> headerBg=new WeakReference<LayerDrawable>((LayerDrawable) getResources().getDrawable(R.drawable.black_bg));
			if (!_course.is_tutorial()) {
				headerBg.get().getDrawable(1).setAlpha(0);
			}
			_detailHeader.setBackgroundDrawable(headerBg.get());
		}		
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	protected void setupDetailContent() {
		_btnUpdateMarks=(Button) findViewById(R.id.btn_update_marks);
		_btnUpdateMarks.setOnClickListener(this);
		
		_txtCourse=(TextView) findViewById(R.id.frm_txt_course);
		_txtDesc=(TextView) findViewById(R.id.frm_txt_desc);
		_txtDueDate=(TextView) findViewById(R.id.frm_txt_duedate);
		_txtWeight=(TextView) findViewById(R.id.frm_txt_weight);
		_txtMarkGrade=(TextView) findViewById(R.id.frm_txt_mark);
		
		String desc=_assignment.get_description();
		String weight=Double.toString(_assignment.get_weight());
		long duedateTime=TimetableHelper.convertFromDateTimeStringToMillis(_assignment.get_DueDate(), TimetableHelper.TYPE_DATE).getTime();
		String duedate=TimetableHelper.getFormattedString(duedateTime, TimetableHelper.TYPE_DATE_WEEKDAY)+" "+_assignment.get_DueTime();
		
		_txtCourse.setText(_course.toString());
		_txtDesc.setText(Validator.checkNonRequiredNull(desc)?desc:DEFAULT_TEXT);
		_txtDueDate.setText(duedate);
		_txtWeight.setText(Validator.checkNonRequiredNull(weight)?weight:DEFAULT_TEXT);
		_txtMarkGrade.setText(_assignment.get_grade().toString());
		
		_currentInputMark=_assignment.get_mark();
		_currentInputTotal=_assignment.get_total();
	}

	@Override
	public void onClick(View v) {
		int id=v.getId();
		//shows an input dialog for updating marks
		if (id==R.id.btn_update_marks) {
			showDialogFragment(InputDialogFragment.newInstance("Add/Update mark", R.layout.dialog_update_marks,"Save"), InputDialogFragment.TAG);
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void setupInputs(View v) {
		EditText txtMark=(EditText) v.findViewById(R.id.frm_txt_mark);
		EditText txtTotal=(EditText) v.findViewById(R.id.frm_txt_total);
		String mark=Double.toString(_currentInputMark);
		String total=Double.toString(_currentInputTotal);
		txtMark.setText(mark);
		txtTotal.setText(total);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void onInputSaveListener(View v) {
		EditText txtMark=(EditText) v.findViewById(R.id.frm_txt_mark);
		EditText txtTotal=(EditText) v.findViewById(R.id.frm_txt_total);
		String mark=txtMark.getText().toString();
		String total=txtTotal.getText().toString();
		
		_validator.reset();
		if(_validator.checkNull(mark, AppUtils.ERROR_MESSAGE_GENERIC_MARK)){
			_currentInputMark=Double.parseDouble(mark);
		}else {
			_currentInputMark=0;
		}
		if (_validator.checkNull(total, AppUtils.ERROR_MESSAGE_GENERIC_TOTAL)) {
			_currentInputTotal=Double.parseDouble(total);
		}else {
			_currentInputTotal=0;
		}
		_validator.checkDecimalMinMax(_currentInputMark, _currentInputTotal, AppUtils.ERROR_MESSAGE_GENERIC_TOTAL_LESS);
		if (_validator.get_errorMessages()!=null) {
			showDialogFragment(InputDialogFragment.newInstance("Add/Update mark", R.layout.dialog_update_marks,"Save"), InputDialogFragment.TAG);
			showDialogFragment(MessageDialogFragment.newInstance("Error - add/update mark", _validator.get_errorMessages()), MessageDialogFragment.TAG);
		}else {
			UofTGrade newMark=new UofTGrade(_currentInputMark, _currentInputTotal, _assignment.get_weight());
			_assignment.set_grade(newMark);
			DatabaseManager.getInstance(this).saveAssignment(_assignment);
			_txtMarkGrade.setText(_assignment.get_grade().toString());
			Toast.makeText(this, "Mark for "+_assignment.get_Title()+" is saved!", Toast.LENGTH_SHORT).show();
			
		}
		
	}

}
